<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <!-- <el-form-item label="广告开始时间" prop="advertisingStarttime">
        <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.advertisingStarttime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择广告开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="广告结束时间" prop="advertisingEndtime">
        <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.advertisingEndtime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择广告结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="广告存放区域标识—外键" prop="advertisingAreaId">
        <el-input
          v-model="queryParams.advertisingAreaId"
          placeholder="请输入广告存放区域标识—外键"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="广告状态" prop="advertisingStatus">
        <el-select v-model="queryParams.advertisingStatus" placeholder="请选择广告状态" clearable size="small">
          <el-option :value="0" label="正常"></el-option>
          <el-option :value="1" label="停用"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:advertising:add']"
        >新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:advertising:edit']"
        >修改</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:advertising:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:advertising:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="advertisingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="广告图片" align="center" prop="advertisingImg">
		  <template style="width: 100px; height: 100px;border-radius: 50%;"
		   slot-scope="scope" v-if="scope.row.advertisingImg != null && scope.row.advertisingImg != ''">
			<el-popover trigger="hover" placement="top">
				<img v-for="(item, index) in scope.row.advertisingImg.split(',')" style="width: 100px;margin-left: 5px;" :key="index" :src="item" />
				<div slot="reference" class="name-wrapper"><el-tag size="medium">查看</el-tag></div>
			</el-popover>
		  </template>
	  </el-table-column>
      <el-table-column label="链接地址" align="center" prop="advertisingUrl" />
      <el-table-column label="广告开始时间" align="center" prop="advertisingStarttime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.advertisingStarttime, '{y}年{m}月{d} {h}时{m}分') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="广告结束时间" align="center" prop="advertisingEndtime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.advertisingEndtime, '{y}年{m}月{d} {h}时{m}分') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="存放区域" align="center" prop="advertisingAreaId">
		  <template slot-scope="scope">
		  	{{scope.row.advertisingArea.advertisingAreaName}}
		  </template>
	  </el-table-column>
      <el-table-column label="广告状态" align="center" prop="advertisingStatus">
		  <template slot-scope="scope">
		  	{{scope.row.advertisingStatus == 0 ? '正常':(scope.row.advertisingStatus == 1 ? '停用' : 'null')}}
		  </template>
	  </el-table-column>
      <el-table-column label="备注" align="center" prop="advertisingContent" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:advertising:edit']"
          >修改</el-button>
         <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:advertising:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改广告管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="广告图片" prop="advertisingImg">
			          <el-upload
			              action="https://jsonplaceholder.typicode.com/posts/"
			            	:auto-upload="false"
			            	ref="upload"
			            	list-type="picture-card"
			            	:http-request="uploadFile"
			            	:limit="1"
			            	:on-preview="handlePictureCardPreview"
			            	:on-remove="handleRemove"
			            	:on-success="imageChange"
			            	:file-list="imageList"
			            ></el-upload>
			            <el-dialog :visible.sync="dialogVisible"><img width="100%" :src="dialogImageUrl" alt="" /></el-dialog>
			        </el-form-item>
        </el-form-item>
        <el-form-item label="链接地址" prop="advertisingUrl">
          <el-input v-model="form.advertisingUrl" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <!-- <el-form-item label="广告开始时间" prop="advertisingStarttime">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.advertisingStarttime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择广告开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="广告结束时间" prop="advertisingEndtime">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.advertisingEndtime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择广告结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="广告存放区域标识—外键" prop="advertisingAreaId">
          <el-input v-model="form.advertisingAreaId" placeholder="请输入广告存放区域标识—外键" />
        </el-form-item> -->
        <el-form-item label="广告状态">
            <el-select v-model="form.advertisingStatus" placeholder="请选择订单状态">
            <el-option :value="0" label="正常"></el-option>
            <el-option :value="1" label="停用"></el-option>
             </el-select>
        </el-form-item>
        <!-- <el-form-item label="备注" prop="advertisingContent">
          <el-input v-model="form.advertisingContent" type="textarea" placeholder="请输入内容" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAdvertising, getAdvertising, delAdvertising, addAdvertising, updateAdvertising, exportAdvertising, uploadImgs } from "@/api/system/advertising";

export default {
  name: "Advertising",
  data() {
    return {
      imgurl:process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 广告管理表格数据
      advertisingList: [],
      // 弹出层标题
      title: "",
	  //开始
		formDate: null,
		uploadList: [],
		dialogImageUrl: '',
		dialogVisible: false,
		imageList: [],
		//结束
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        advertisingImg: undefined,
        advertisingUrl: undefined,
        advertisingStarttime: undefined,
        advertisingEndtime: undefined,
        advertisingAreaId: undefined,
        advertisingStatus: undefined,
        advertisingContent: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询广告管理列表 */
    getList() {
      this.loading = true;
      listAdvertising(this.queryParams).then(response => {
        this.advertisingList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
		this.imageList = [];
      this.form = {
        advertisingId: undefined,
        advertisingImg: undefined,
        advertisingUrl: undefined,
        advertisingStarttime: undefined,
        advertisingEndtime: undefined,
        advertisingAreaId: undefined,
        advertisingStatus: "0",
        advertisingContent: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.advertisingId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加广告管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const advertisingId = row.advertisingId || this.ids
      getAdvertising(advertisingId).then(response => {
		   if (response.data.advertisingImg != null && response.data.advertisingImg != '') {/* 判断图片的地址是否为空 */
		          	var imageList = response.data.advertisingImg.split(',');
		          	for (var i = 0; i < imageList.length; i++) {
		          		imageList[i] = imageList[i];
		          		this.imageList.push({
		          			name: imageList[i],
		          			url: imageList[i]
		          		});
		          	}
		          }
        this.form = response.data;
        this.open = true;
        this.title = "修改广告管理";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
	    this.formDate = new FormData();//图片
	    this.$refs.upload.submit();
	    console.log(this.formDate);
		 if (this.uploadList.length > 0) {
		      	this.uploadList = [];
		      	uploadImgs(this.formDate).then(responses => {
		      		this.formDate = null;
		      		if (responses.code === 200) {
		      			this.$refs.upload.clearFiles();//清除上传列表
		      			var imageList = [];
		      			if (this.imageList != null) {
		      				for (var i = 0; i < this.imageList.length; i++) {
		      					if (this.imageList[i] != null) {
		      						imageList.push(this.imageList[i].name);
		      					}
		      				}
		      			}
		      			imageList = imageList.concat(responses.data);
		            console.log(responses.data);
		      			this.form.advertisingImg = imageList.join(',');
		      			this.submitForms();
		      		} else {
		      			this.msgError(responses.msg);
		      		}
		      	});
		      }else {
      	this.formDate = null;
      	var imageList = [];
      	if (this.imageList != null) {
      		for (var i = 0; i < this.imageList.length; i++) {
      			if (this.imageList[i] != null) {
      				imageList.push(this.imageList[i].name);
      			}
      		}
      	}
        console.log(imageList);
      	this.form.advertisingImg = imageList.join(',');
      	this.submitForms();
      }
	  },submitForms:function(){
		  this.$refs["form"].validate(valid => {
		    if (valid) {
		      if (this.form.advertisingId != undefined) {
		        updateAdvertising(this.form).then(response => {
		          if (response.code === 200) {
		            this.msgSuccess("修改成功");
		            this.open = false;
		            this.getList();
		          }
		        });
		      } else {
		        addAdvertising(this.form).then(response => {
		          if (response.code === 200) {
		            this.msgSuccess("新增成功");
		            this.open = false;
		            this.getList();
		          }
		        });
		      }
		    }
		  });
	  },
    /** 删除按钮操作 */
    handleDelete(row) {
      const advertisingIds = row.advertisingId || this.ids;
      this.$confirm('是否确认删除广告管理编号为"' + advertisingIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delAdvertising(advertisingIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有广告管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportAdvertising(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
	 /** 图片操作 */
	    handleRemove(file, fileList) {//删除时
	    	for (var i = 0; i < this.imageList.length; i++) {
	    		if (this.imageList[i].url == file.url) {
	    			this.imageList.splice(i, 1);
	    		}
	    	}
	    },
	    handlePictureCardPreview(file) {//上传文件时
	      console.log(file.url);
	    	this.dialogImageUrl = file.url;
	    	this.dialogVisible = true;
	    },
	    imageChange(event, file, fileList) {//成功后
	     /* alert("123成功"); */
	    	console.log(event);
	    	console.log(file);
	    	console.log(fileList);
	    },
	    uploadFile(file) {//上传行为
	    	this.uploadList.push(file.file);
	    	this.formDate.append('file', file.file);
	      console.log(this.formDate.file);
	    }
  }
};
</script>